import { Component, OnInit, Input, Injector } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { DataDictionaryService } from 'services';
import { ModalComponentBase } from '@shared/component-base';
import { DataDictionary } from 'entities';

@Component({
  selector: 'app-create-or-update-datadictionary',
  templateUrl: './create-or-update-datadictionary.component.html',
  styles: [],
  providers: [DataDictionaryService],
})
export class CreateOrUpdateDatadictionaryComponent extends ModalComponentBase
  implements OnInit {
  @Input() id: number;
  @Input() group: any;
  @Input() parent: any;
  @Input() codes: any[];

  title: string;
  form: FormGroup;
  dataDictionary: DataDictionary = new DataDictionary();
  constructor(
    injector: Injector,
    private dataDictionaryService: DataDictionaryService,
    private fb: FormBuilder,
  ) {
    super(injector);
  }

  ngOnInit() {
    if (this.group.mode != 3) {
      this.form = this.fb.group({
        code: [null, Validators.compose([Validators.required, Validators.maxLength(100), this.checkDataValidator])],
        desc: [null, Validators.compose([Validators.maxLength(100), Validators.required])],
        seq: [null, Validators.compose([Validators.pattern('^[0-9]*$'), Validators.required])],
      });
    } else {
      this.form = this.fb.group({
        code: [null, Validators.compose([Validators.required, Validators.maxLength(100), this.checkDataValidator])],
        value: [null, Validators.compose([Validators.maxLength(25), Validators.required])],
        desc: [null, Validators.compose([Validators.maxLength(100), Validators.required])],
        seq: [null, Validators.compose([Validators.pattern('^[0-9]*$'), Validators.required])],
      });
    }

    if (this.id) {
      this.getData();
      this.title = '编辑';
    } else {
      this.dataDictionary.group = this.group.id;
      this.title = '新增';
    }
  }

  getData() {
    this.dataDictionaryService.getById(this.id.toString()).subscribe(result => {
      this.dataDictionary = result;
    });
  }

  save() {
    this.dataDictionary.parentId = this.parent ? this.parent.id : 0;
    //alert(this.dataDictionary.parentId)
    if (this.group.mode != 3) {
      this.dataDictionary.value = this.dataDictionary.code;
    }
    this.dataDictionaryService
      .createOrUpdate(this.dataDictionary)
      .finally(() => {
        this.saving = false;
      })
      .subscribe(() => {
        this.notify.success('保存成功！');
        this.success();
      });
  }

  checkDataValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (this.codes.indexOf(control.value) > -1) {
      return { repeat: true, error: true };
    }
  }
}
